//
//  AlarmClockViewController.m
//  AlarmClock
//
//  Created by apple on 16/9/28.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AlarmClockViewController.h"
#import "AlarmClockTableViewCell.h"
#import "AddAlarmClockViewController.h"
#import "SDAutoLayout.h"
#import "BSKConsts.h"
#import "BSKCancelAlarmClockViewController.h"
#import "AgainBellView.h"
#import "UILocalNotification+setAlarmclock.h"
#import "UIViewController+BSKToast.h"
#import "BSKSington.h"
@interface AlarmClockViewController ()<UITableViewDelegate,UITableViewDataSource,BSKCancelAlarmClockViewControllerDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIButton *addButton;
@property (nonatomic,strong) UIButton *settingButton;
@property (nonatomic,strong) UIView *lineView;
@property (nonatomic,strong) UILabel *addLabel;
@property (nonatomic,strong) UILabel *settingLabel;
@property (nonatomic,strong) NSMutableArray *dataSource;
@end

@implementation AlarmClockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeAperance];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wakeUpMessage:) name:@"UILocalNotification" object:nil];
}

-(void)wakeUpMessage:(NSNotification *)notification{
    UILocalNotification * localNotify = notification.object[@"notify"];
    
    NSDictionary * agaginDic = [[NSUserDefaults standardUserDefaults]objectForKey:@"setting"];
    BSKCancelAlarmClockViewController *vc = [[BSKCancelAlarmClockViewController alloc]initWithMode:BSKCancelAlarmClockVCAlarmClockHardMode];
    vc.playSound = YES;
    vc.dic = localNotify.userInfo;
    vc.delegate = self;
    vc.moreMinutes = [agaginDic[@"again"] integerValue];
//    [self presentViewController:vc animated:YES completion:nil];
    
    [[BSKSington sharBSKSington].rootViewController pushViewController:vc animated:YES];
    [[UIApplication sharedApplication] cancelLocalNotification:localNotify];
    
    if ([localNotify.userInfo[@"repeat"] isEqualToString:@"只响一次"]) {
        NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"];
        NSMutableArray *newArray = @[].mutableCopy;
        for (NSDictionary *dic in array) {
            NSMutableDictionary *newDic = [dic mutableCopy];
            if ([localNotify.userInfo[@"alarmClockId"] isEqualToString:dic[@"alarmClockId"]]) {
                [newDic setValue:@"NO" forKey:@"isStart"];
            }
            [newArray addObject:newDic];
        }
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"alarmClock"];
        [[NSUserDefaults standardUserDefaults] setObject:newArray forKey:@"alarmClock"];
        [self.tableView reloadData];
    }
    
}

#pragma mark BSKCancelAlarmClockViewControllerDelegate
-(void)CancelAlarmClockVC:(BSKCancelAlarmClockViewController *)vc didClosed:(BOOL)closed{
    // 关闭闹钟
    NSArray * notis = [UIApplication sharedApplication].scheduledLocalNotifications;
    for (UILocalNotification * noti in notis) {
        if ([[noti.userInfo objectForKey:@"alarmClockId"] isEqualToString:vc.dic[@"alarmClockId"]]) {
            [[UIApplication sharedApplication] cancelLocalNotification:noti];
        }
    }
    // 通知下一次闹钟时间
    [UILocalNotification setNextAlrmClockWhithInfoDic:vc.dic];
}


-(void)CancelAlarmClockVC:(BSKCancelAlarmClockViewController *)vc moreMinutesAction:(NSInteger)minutes{
    // 关闭闹钟
    NSArray * notis = [UIApplication sharedApplication].scheduledLocalNotifications;
    for (UILocalNotification * noti in notis) {
        if ([[noti.userInfo objectForKey:@"alarmClockId"] isEqualToString:vc.dic[@"alarmClockId"]]) {
            [[UIApplication sharedApplication] cancelLocalNotification:noti];
        }
    }
    // 再睡的时间
    NSDictionary * agaginDic = [[NSUserDefaults standardUserDefaults]objectForKey:@"setting"];
    NSInteger second = [agaginDic[@"again"] integerValue];
    // 重复响铃次数
    NSMutableDictionary * mdic = [vc.dic mutableCopy];
    NSNumber * count = mdic[@"againCount"];
    NSInteger countNumber = 0;
    if (!count) {
        countNumber =[agaginDic[@"count"] integerValue];
        [mdic setObject:@(countNumber) forKey:@"againCount"];
        
    }else{
        countNumber = [count integerValue]-1;
        mdic[@"againCount"] = @(countNumber);
    }
    
    if (countNumber >= 0) {
        // 发送本地通知
        [UILocalNotification setNextAlrmClockWhithInfoDic:[mdic copy] MoreTime:second];
//        [self dismissViewControllerAnimated:YES completion:nil];
        
        [[BSKSington sharBSKSington].rootViewController popViewControllerAnimated:YES];
        
    } else {
        [self MakeToast:@"重复响铃次数已用完" WithTime:2];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"nextCount"];
    }
}



- (void)viewWillAppear:(BOOL)animated {
    NSMutableArray *array = @[].mutableCopy;
    array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
    if (array.count > 0) {
        self.dataSource = array;
    } else {
        self.dataSource = nil;
    }
    [self.tableView reloadData];
    
    //[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"setting"];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"setting"];
    if (dic.count == 0) {
        dic = @{@"again":@"5",@"count":@"1"};
        [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"setting"];
    }
    //NSLog(@" ******  %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"setting"]);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"notice"];
}

#pragma mark - private method
- (void)initializeAperance {
    self.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.settingButton];
    [self.view addSubview:self.addLabel];
    [self.view addSubview:self.settingLabel];
    self.dataSource = @[].mutableCopy;
    
    self.lineView.sd_layout
    .topSpaceToView(self.view,8)
    .leftSpaceToView(self.view,30)
    .rightSpaceToView(self.view,30)
    .heightIs(1);
    
    self.tableView.sd_layout
    .topSpaceToView(self.view,10)
    .leftSpaceToView(self.view,10)
    .rightSpaceToView(self.view,30)
    .bottomSpaceToView(self.view,150);
    
    self.addButton.sd_layout
    .leftSpaceToView(self.view,self.view.width / 2 - self.view.width/3)
    .widthIs(self.view.width/3-10)
    .heightEqualToWidth()
    .bottomSpaceToView(self.view,40);
    
    self.settingButton.sd_layout
    .leftSpaceToView(self.view,self.view.width / 2 + 10)
    .widthIs(self.view.width/3-10)
    .heightEqualToWidth()
    .bottomSpaceToView(self.view,40);
    
    self.addLabel.sd_layout
    .leftEqualToView(self.addButton)
    .rightEqualToView(self.addButton)
    .heightIs(30)
    .topSpaceToView(self.addButton,0);
    
    self.settingLabel.sd_layout
    .leftEqualToView(self.settingButton)
    .rightEqualToView(self.settingButton)
    .heightIs(30)
    .topSpaceToView(self.settingButton,0);
}

#pragma mark - action

- (void)addButtonPressed:(UIButton *)sender {
    AddAlarmClockViewController *add = [[AddAlarmClockViewController alloc]init];
//    [self presentViewController:add animated:YES completion:nil];
    
    [[BSKSington sharBSKSington].rootViewController pushViewController:add animated:YES];
}

- (void)settingButtonPressed:(UIButton *)sender {
     UIViewController *controller = [[UIApplication sharedApplication] keyWindow].rootViewController;
    AgainBellView *again = [[AgainBellView alloc]initWithFrame:controller.view.bounds];
    [controller.view addSubview:again];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"setting"];
    NSInteger againValue;
    NSInteger countValue;
    if (dic.count > 0) {
        againValue = [dic[@"again"] intValue];
        countValue = [dic[@"count"] intValue];
    } else {
        againValue = 0;
        countValue = 0;
    }
    [again show:CGRectMake(20, (ScreenHeight-ScreenHeight/1.8)/2, ScreenWidth - 40, ScreenHeight/1.8) againValue:againValue countValue:countValue];
    again.againBellViewHandle = ^(NSInteger index,NSInteger count) {
        NSString *againString;
        NSString *countString;
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"setting"];
        if (count == 4) {
            againString = [NSString stringWithFormat:@"%ld",index * 5];
            countString = @"10";
        } else {
            againString = [NSString stringWithFormat:@"%ld",index * 5];
            countString = [NSString stringWithFormat:@"%ld",count * 2 - 1];
        }
        NSDictionary *dic = @{@"again":againString,@"count":countString};
        [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"setting"];
        [[NSUserDefaults standardUserDefaults] setObject:@{@"nextCount":countString} forKey:@"nextCount"];
    };
}



#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"alarmClock";
    AlarmClockTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[AlarmClockTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = self.dataSource[indexPath.row];
    cell.dateId = dic[@"alarmClockId"];
    cell.index = indexPath.row;
    //NSLog(@"---------------- %@",dic[@"alarmClockId"]);
    cell.alarmClockLabel.text = dic[@"date"];
    if ([dic[@"repeat"] isEqualToString:@"星期日|星期一|星期二|星期三|星期四|星期五|星期六"])
    {
        cell.numberLabel.text = @"每天";
    } else if ([dic[@"repeat"] isEqualToString:@"星期一|星期二|星期三|星期四|星期五"])
    {
        cell.numberLabel.text = @"周一到周五";
    } else {
      cell.numberLabel.text = dic[@"repeat"];
    }
    
    if ([dic[@"isStart"] isEqualToString:@"YES"]) {
        cell.alarmSwitch.on = YES;
        cell.alarmClockLabel.textColor = [UIColor whiteColor];
        cell.startLabel.text = @"开启";
    } else {
        cell.alarmSwitch.on = NO;
        cell.alarmClockLabel.textColor = [UIColor grayColor];
        cell.startLabel.text = @"未开启";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AddAlarmClockViewController *add = [[AddAlarmClockViewController alloc]init];
    add.isSelected = YES;
    add.index = indexPath.row;
//    [self presentViewController:add animated:YES completion:nil];
    
    [[BSKSington sharBSKSington].rootViewController pushViewController:add animated:YES];
}

#pragma mark - getter
- (UITableView *)tableView {
    if (_tableView) {
        return _tableView;
    }
    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 100;
    _tableView.backgroundColor = [UIColor clearColor];
    return _tableView;
}

- (UIView *)lineView {
    if (_lineView) {
        return _lineView;
    }
    _lineView = [[UIView alloc]init];
    _lineView.backgroundColor = [UIColor whiteColor];
    _lineView.alpha = 0.5;
    return _lineView;
}
- (UIButton *)addButton {
    if (_addButton) {
        return _addButton;
    }
    _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addButton setImage:[UIImage imageNamed:@"alarm_btn_add_normal"] forState:UIControlStateNormal];
    [_addButton addTarget:self action:@selector(addButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    return _addButton;
}

- (UIButton *)settingButton {
    if (_settingButton) {
        return _settingButton;
    }
    _settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_settingButton setImage:[UIImage imageNamed:@"alarm_btn_setting_normal"] forState:UIControlStateNormal];
    [_settingButton addTarget:self action:@selector(settingButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    return _settingButton;
}

- (UILabel *)addLabel {
    if (_addLabel) {
        return _addLabel;
    }
    _addLabel = [[UILabel alloc]init];
    _addLabel.text = @"新建";
    _addLabel.textAlignment = NSTextAlignmentCenter;
    _addLabel.textColor = [UIColor whiteColor];
    return _addLabel;
}

- (UILabel *)settingLabel {
    if (_settingLabel) {
        return _settingLabel;
    }
    _settingLabel = [[UILabel alloc]init];
    _settingLabel.text = @"设置";
    _settingLabel.textAlignment = NSTextAlignmentCenter;
    _settingLabel.textColor = [UIColor whiteColor];
    return _settingLabel;
}

@end
